import { Button, Card, Form, Input, message, Select, Space } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import Table, { ColumnsType } from "antd/lib/table";
import {
  reqGetCityOrDistrict,
  reqGetHospitalList,
  reqGetProvinces,
} from "@/api/hospital/hospitalList/hospitalList";
import {
  HospitalListItems,
  ProvinceItems,
} from "@/api/hospital/hospitalList/model/hospitalTypes";
import { Link } from "react-router-dom";
import {reqUpdateHospitalStatus} from '@api/hospital/hospitalList/hospitalList';

export default function HospitalList() {
  //创建 form 对象
  let [form] = Form.useForm();
  //声明状态
  let [fields, setFields] = useState<any>({});
  //声明状态
  let [flag, setFlag] = useState(false);
  //声明一个函数
  function update(){
    setFlag(!flag);
  }
  //创建事件回调
  let finish = () => {
    //获取表单元素的值
    let fields = form.getFieldsValue();
    //发送 AJAX 请求
    setFields(fields);
  };
  //表格列结构
  let columns: ColumnsType<any> = [
    {
      title: "序号",
      width: 70,
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "医院 logo",
      dataIndex: "logoData",
      render: (value) => {
        return (
          <img width="60" src={`data:image/png;base64, ${value}`} alt="" />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render: (value, row) => {
        return row.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      width: 220,
      render: (value, row) => {
        return row.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (value) => {
        return value === 1 ? "已上线" : "已下线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      fixed: "right",
      width: 250,
      render: (value, row) => {
        return (
          <Space>
            <Link to={`/syt/hospital/hospitalList/show/${row.id}`}><Button type="primary">查看</Button></Link>
            <Link to={`/syt/hospital/hospitalList/schedule/${row.hoscode}`}><Button type="primary">排班</Button></Link>
            <Button type="primary" onClick={async () => {
              await reqUpdateHospitalStatus(row.id, row.status ? 0 : 1);
              //提示
              message.success('更新成功');
              //更新组件
              update();
            }}>{row.status ? '下线' : '上线'}</Button>
          </Space>
        );
      },
    },
  ];

  //声明与分页相关的状态
  let [current, setCurrent] = useState<number>(1);
  let [total, setTotal] = useState<number>(0);
  let [pageSize, setPageSize] = useState<number>(5);
  //声明状态 管理省份信息
  let [province, setProvince] = useState<ProvinceItems>([]);
  let [city, setCity] = useState<ProvinceItems>([]);
  let [district, setDistrict] = useState<ProvinceItems>([]);
  //医院类型状态
  let [hosTypes, setHosTypes] = useState<ProvinceItems>([]);
  //医院列表的装填
  let [hospitalList, setHospitalList] = useState<HospitalListItems>([]);
  //loading 效果
  let [loading, setLoading] = useState(false);

  //组件挂载完毕
  useEffect(() => {
    //获取省份信息
    let getProvince = async () => {
      let provinces = await reqGetProvinces("Province");
      //更新状态
      setProvince(provinces);
    };
    getProvince();

    //获取医院类型信息
    let getHosTypes = async () => {
      let hostypes = await reqGetProvinces("HosType");
      setHosTypes(hostypes);
    };
    getHosTypes();
  }, []);

  //声明函数            省份的 id
  let getCity = async (id: number) => {
    //清空城市的列表
    setCity([]);
    setDistrict([]);
    //修改城市下拉框的值
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });
    //发送请求获取城市的列表
    let citys = await reqGetCityOrDistrict(id);
    //设置状态
    setCity(citys);
  };

  //获取区县的信息
  let getDistrict = async (id: number) => {
    //清空区县的列表
    setDistrict([]);
    //修改区县的值为 undefined
    form.setFieldsValue({ districtCode: undefined });
    //发送请求
    let district = await reqGetCityOrDistrict(id);
    //更新状态
    setDistrict(district);
  };

  //组件挂载完毕钩子 发送请求
  useEffect(() => {
    let getHospital = async () => {
      //设置为发送中...
      setLoading(true);
      try {
        //发送请求
        let result = await reqGetHospitalList({
          page: current,
          limit: pageSize,
          ...fields
        });
        //将结果的数据 呈现在表格中
        setHospitalList(result.content);
        //更新表格数据的总数
        setTotal(result.totalElements);
        //设置为未加载中...
        setLoading(false);
      } catch (e) {
        setLoading(false);
      }
    };
    getHospital();
  }, [current, pageSize, fields, flag]);

  return (
    <Card>
      {/* 表单部分 */}
      <Form form={form} layout="inline" onFinish={finish}>
        <Form.Item style={{ width: 200, marginBottom: 20 }} name="provinceCode">
          <Select placeholder="请选择省" onChange={getCity}>
            {province.map((item) => {
              return (
                <Select.Option key={item.id} value={item.value}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item style={{ width: 200 }} name="cityCode">
          <Select placeholder="请选择市" onChange={getDistrict}>
            {city.map((item) => {
              return (
                <Select.Option key={item.id} value={item.value}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item style={{ width: 200 }} name="districtCode">
          <Select placeholder="请选择区">
            {district.map((item) => {
              return (
                <Select.Option key={item.id} value={item.value}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item style={{ width: 200 }} name='hostype'>
          <Select placeholder="医院类型">
            {hosTypes.map((item) => {
              return (
                <Select.Option key={item.id} value={item.value}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item style={{ width: 200 }} name="status">
          <Select placeholder="医院状态">
            <Select.Option value="1">上线</Select.Option>
            <Select.Option value="0">下线</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button htmlType="reset">清空</Button>
          </Space>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 表格部分 */}
      <Table
        columns={columns}
        dataSource={hospitalList}
        rowKey="id"
        bordered
        loading={loading}
        scroll={{ x: 1300 }}
        pagination={{
          current: current,
          total: total,
          pageSize: pageSize,
          onChange: (page: number, pageSize: number) => {
            //更新状态
            setCurrent(page);
            //更新每页显示的数量
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
}
